/*
 * @Descripttion: 
 * @Author: xiaodong
 * @Date: 2020-09-17 15:11:28
 * @LastEditTime : 2020-11-26 19:00:28
 * @FilePath     : e:\云设计\微服务\新建文件夹\cloud-design-center-tool\src\store\modules\components\user.js
 */
const userKey = 'dcc_user',
  authKey = process.env.VUE_APP_authorization,

  mutationTypes = {
    SET_USERINFO: 'SET_USERINFO'           // 设置/更新 用户信息数据
  },

  actionTypes = {
  },

  state = {
    userInfo: getUserInfo()
  },

  getters = {
    
  },

  mutations = {
    [mutationTypes.SET_USERINFO](state, params) {
      localStorage.removeItem(userKey);
      localStorage.removeItem(authKey);
      localStorage.setItem(userKey, JSON.stringify(params));
      localStorage.setItem(authKey, getAuth());
      state.userInfo = Object.assign({}, params);
    }
  },


  actions = {
    // 设置用户消息
    setUserInfo({ commit }, data) {
      commit('SET_USERINFO', data);
    }
  };

export default {
  state,
  getters,
  mutations,
  actions,
  mutationTypes,
  actionTypes,
  namespaced: true
};

function getUserInfo(){
  const auth = getAuth(),
    localAuth = localStorage.getItem(authKey);
  if(auth&&localAuth&&auth===localAuth){
    try {
      return JSON.parse(localStorage.getItem(userKey));
    } catch (error) {
      return {};
    }
  }  
  return {};
}

function getAuth(){
  const reg =  new RegExp(`(?:(?:^|.*;\\s*)${authKey}\\s*\\=\\s*([^;]*).*$)|^.*$`),
    val = document.cookie.replace(reg, '$1');
  return val;
}